import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent

import java.sql.{Connection, DriverManager}


//11
object GenderStream {
  private val jdbcUrl = "jdbc:mysql://localhost:3306/stats?serverTimezone=Asia/Shanghai"
  private val dbUser = "root"
  private val dbPassword = "123456"

  def getConnection(): Connection = {
    DriverManager.getConnection(jdbcUrl, dbUser, dbPassword)
  }

  def updateGenderStats(semester: Int, gender: String, count: Int): Unit = {


//    val jdbcUrl = "jdbc:mysql://localhost:3306/stats?serverTimezone=Asia/Shanghai"
//    val dbUser = "root"
//    val dbPassword = "123456"

    val sql = "INSERT INTO gender_stats0 (semester, gender, count) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE count=count+?"
    val conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword)
    try {
      val stmt = conn.prepareStatement(sql)
      stmt.setInt(1, semester)
      stmt.setString(2, gender)
      stmt.setInt(3, count)
      stmt.setInt(4, count)
      stmt.executeUpdate()
    } finally {
      if (!conn.isClosed()) conn.close()
    }
  }

  def main(args: Array[String]): Unit = {

    // Spark 配置
    val conf = new SparkConf().setMaster("local[*]").setAppName("KafkaSparkStream")
    val ssc = new StreamingContext(conf, Seconds(2))

    ssc.sparkContext.setLogLevel("error")
    // Kafka 配置
    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "192.168.244.11:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "hael2",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    val topics = Array("lol")
    val stream = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )
    val genderCounts = stream.map(record => record.value.split("\t"))
      .filter(_.length == 7) // 确保我们只处理正确的记录
      .map(fields => ((fields(5), if (fields(2).trim == "1") "male" else "female"), 1))
      .reduceByKey(_ + _)

    genderCounts.foreachRDD { rdd =>
      rdd.collect().foreach { case ((semester, gender), count) =>
        updateGenderStats(semester.toInt, gender, count)
        println(s"Updated stats in MySQL: Semester $semester, Gender $gender -> $count")
      }
    }


    // 启动 Spark Streaming
    ssc.start()
    ssc.awaitTermination()

  }
}
